﻿using CRM.Infrastructure.Dto;
using CRM.Infrastructure.Models;
using Dapper;
using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace CRM.Infrastructure.Repository
{
    public class CallReportRepository
    {
        DatabaseContext dbContext = new DatabaseContext();


        public Page<CallDto> GetPages(SearchCallModel model)
        {
            string sql = @" SELECT T.ClueID,T.RingTime,T1.BgnTime,T1.EndTime,T1.AgentAlertTime,T1.FileName,T1.Directory,T2.UserName,T2.Brand,T2.Model
                            FROM [CallRing] T 
                            LEFT JOIN CallEnd T1 ON T1.CallID = T.CallID
                            LEFT JOIN Clues T2 ON T.ClueID=T2.ClueID
                            WHERE 1=1";
            StringBuilder sb = new StringBuilder(sql);
            var dparams = new DynamicParameters();
            AddParams(model, sb, dparams);
            return dbContext.Connection.Page<CallDto>(model.PageIndex, model.PageSize, sb.ToString(), dparams);

        }

        /// <summary>
        /// 构建查询条件
        /// </summary>
        /// <param name="model"></param>
        /// <param name="sb"></param>
        /// <param name="dparams"></param>
        private void AddParams(SearchCallModel model, StringBuilder sb, DynamicParameters dparams)
        {
            if (model.ClueID > 0)
            {
                sb.Append(" AND T.ClueID=@ClueID");
                dparams.Add("ClueID", model.ClueID, System.Data.DbType.Int32);
            }

            if (model.CompanyID > 0)
            {
                sb.Append(" AND T2.CompanyID=@CompanyID");
                dparams.Add("CompanyID", model.CompanyID, System.Data.DbType.Int32);
            }           

            if (model.BCreateDate.Year > 1900)
            {
                sb.Append(" AND T.RingTime>@BCreateDate");
                dparams.Add("BCreateDate", model.BCreateDate.AddDays(-1).Date.ToString("yyyyMMddHHmmss"), System.Data.DbType.String);
            }

            if (model.ECreateDate.Year > 1900)
            {
                sb.Append(" AND T.RingTime<@ECreateDate");
                dparams.Add("ECreateDate", model.ECreateDate.AddDays(1).Date.ToString("yyyyMMddHHmmss"), System.Data.DbType.String);
            }

            if (!string.IsNullOrWhiteSpace(model.Brand))
            {
                sb.Append(" AND charindex(@Brand,T2.Brand)>0");
                dparams.Add("Brand", model.Brand, System.Data.DbType.String);
            }

            if (!string.IsNullOrWhiteSpace(model.CModel))
            {
                sb.Append(" AND charindex(@CModel,T2.Model)>0");
                dparams.Add("CModel", model.CModel, System.Data.DbType.String);
            }
        }

    }
}